package com.geekbg.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author pizhihui
 * @date 2023-02-24 18:13
 */
public class ZkClientUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZkClientUtil.class);

    private static String zkPath = "";

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    private static ZooKeeper zk;

    static {
        try {
            zk = new ZooKeeper(zkPath, 1000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    LOGGER.info("已经触发了 {} 事件", event.getType());
                    connectedSemaphore.countDown();
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static ZooKeeper getConnection() {
        try {
            if (null == zk) {
                connectedSemaphore.await();
            }
            return zk;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
